package com.example.demo;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.example.demo.util.FileUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class JsonRequestWithHttpClient2 {

    public static void main(String[] args) throws Exception {
    	Gson gson = new Gson();
    	String fileName = "D:\\temp\\result.txt";
    	
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("https://medium.com/_/graphql");

        String from = "100";
        Integer limit = 20;
    	requestData(gson, fileName, httpClient, httpPost, from, limit);
        
        httpClient.close();
    }

	private static boolean requestData(Gson gson, String fileName, CloseableHttpClient httpClient, HttpPost httpPost,
			String from, Integer limit) throws IOException, ClientProtocolException {
		StringBuilder sb = new StringBuilder();
        String jsonInputString = "[{\"operationName\":\"CuratedHomeFeedModuleQuery\""
        		+ ",\"variables\":{\"paging\":{\"from\":\""+from+"\",\"limit\":"+limit+"}}"
        		+ ",\"query\":\"query CuratedHomeFeedModuleQuery($paging: PagingOptions!) {\\n  staffPicksFeed(input: {paging: $paging}) {\\n    items {\\n      ...CuratedHomeFeedItems_homeFeedItems\\n      __typename\\n    }\\n    pagingInfo {\\n      next {\\n        page\\n        limit\\n        from\\n        __typename\\n      }\\n      __typename\\n    }\\n    __typename\\n  }\\n}\\n\\nfragment CuratedHomeFeedItems_homeFeedItems on HomeFeedItem {\\n  __typename\\n  post {\\n    id\\n    title\\n    ...HomeFeedItem_post\\n    __typename\\n  }\\n}\\n\\nfragment HomeFeedItem_post on Post {\\n  __typename\\n  id\\n  title\\n  firstPublishedAt\\n  mediumUrl\\n  collection {\\n    id\\n    name\\n    domain\\n    logo {\\n      id\\n      __typename\\n    }\\n    __typename\\n  }\\n  creator {\\n    id\\n    name\\n    username\\n    imageId\\n    mediumMemberAt\\n    __typename\\n  }\\n  previewImage {\\n    id\\n    __typename\\n  }\\n  previewContent {\\n    subtitle\\n    __typename\\n  }\\n  readingTime\\n  tags {\\n    ...TopicPill_tag\\n    __typename\\n  }\\n  ...BookmarkButton_post\\n  ...OverflowMenuButtonWithNegativeSignal_post\\n  ...PostPresentationTracker_post\\n  ...PostPreviewAvatar_post\\n  ...Star_post\\n}\\n\\nfragment TopicPill_tag on Tag {\\n  __typename\\n  id\\n  displayTitle\\n  normalizedTagSlug\\n}\\n\\nfragment BookmarkButton_post on Post {\\n  visibility\\n  ...SusiClickable_post\\n  ...AddToCatalogBookmarkButton_post\\n  __typename\\n  id\\n}\\n\\nfragment SusiClickable_post on Post {\\n  id\\n  mediumUrl\\n  ...SusiContainer_post\\n  __typename\\n}\\n\\nfragment SusiContainer_post on Post {\\n  id\\n  __typename\\n}\\n\\nfragment AddToCatalogBookmarkButton_post on Post {\\n  ...AddToCatalogBase_post\\n  __typename\\n  id\\n}\\n\\nfragment AddToCatalogBase_post on Post {\\n  id\\n  isPublished\\n  __typename\\n}\\n\\nfragment OverflowMenuButtonWithNegativeSignal_post on Post {\\n  id\\n  visibility\\n  ...OverflowMenuWithNegativeSignal_post\\n  __typename\\n}\\n\\nfragment OverflowMenuWithNegativeSignal_post on Post {\\n  id\\n  creator {\\n    id\\n    __typename\\n  }\\n  collection {\\n    id\\n    __typename\\n  }\\n  ...OverflowMenuItemUndoClaps_post\\n  ...AddToCatalogBase_post\\n  __typename\\n}\\n\\nfragment OverflowMenuItemUndoClaps_post on Post {\\n  id\\n  clapCount\\n  ...ClapMutation_post\\n  __typename\\n}\\n\\nfragment ClapMutation_post on Post {\\n  __typename\\n  id\\n  clapCount\\n  ...MultiVoteCount_post\\n}\\n\\nfragment MultiVoteCount_post on Post {\\n  id\\n  __typename\\n}\\n\\nfragment PostPresentationTracker_post on Post {\\n  id\\n  visibility\\n  previewContent {\\n    isFullContent\\n    __typename\\n  }\\n  collection {\\n    id\\n    slug\\n    __typename\\n  }\\n  __typename\\n}\\n\\nfragment PostPreviewAvatar_post on Post {\\n  __typename\\n  id\\n  collection {\\n    id\\n    name\\n    ...CollectionAvatar_collection\\n    __typename\\n  }\\n  creator {\\n    id\\n    username\\n    name\\n    ...UserAvatar_user\\n    ...userUrl_user\\n    ...useIsVerifiedBookAuthor_user\\n    __typename\\n  }\\n}\\n\\nfragment CollectionAvatar_collection on Collection {\\n  name\\n  avatar {\\n    id\\n    __typename\\n  }\\n  ...collectionUrl_collection\\n  __typename\\n  id\\n}\\n\\nfragment collectionUrl_collection on Collection {\\n  id\\n  domain\\n  slug\\n  __typename\\n}\\n\\nfragment UserAvatar_user on User {\\n  __typename\\n  id\\n  imageId\\n  mediumMemberAt\\n  membership {\\n    tier\\n    __typename\\n    id\\n  }\\n  name\\n  username\\n  ...userUrl_user\\n}\\n\\nfragment userUrl_user on User {\\n  __typename\\n  id\\n  customDomainState {\\n    live {\\n      domain\\n      __typename\\n    }\\n    __typename\\n  }\\n  hasSubdomain\\n  username\\n}\\n\\nfragment useIsVerifiedBookAuthor_user on User {\\n  verifications {\\n    isBookAuthor\\n    __typename\\n  }\\n  __typename\\n  id\\n}\\n\\nfragment Star_post on Post {\\n  id\\n  creator {\\n    id\\n    __typename\\n  }\\n  __typename\\n}\\n\"}"
        		+ "]";

        // 设置请求体与Content-Type
        StringEntity entity = new StringEntity(jsonInputString, "UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

            // 输出响应内容（假设是JSON）
            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(result);
            List<Map<String, Object>> list = gson.fromJson(result, new TypeToken<List<Map<String, Object>>>(){}.getType());
            for (Map<String, Object> map : list) {
            	Map<String, Object> map2 = (Map<String, Object>) map.get("data");
            	Map<String, Object> map3 = (Map<String, Object>) map2.get("staffPicksFeed");
            	List<Map<String, Object>> list2 = (List<Map<String, Object>>) map3.get("items");
            	if(list2.isEmpty()) {
            		return false;
            	}
            	for (Map<String, Object> map2_1 : list2) {
                	Map<String, Object> post = (Map<String, Object>) map2_1.get("post");
                	String title = (String) post.get("title");
                	String mediumUrl = (String) post.get("mediumUrl");
                	Double clapCount = (Double) post.get("clapCount");
                	sb.append(title).append("\t")
                		.append(mediumUrl).append("\t")
                		.append(clapCount).append("\t")
                    	.append("\r\n");
				}
			}
//            AppendStringToFile.appendStringToFile(sb.toString(), fileName);
            
        } finally {
            response.close();
        }
        
        return true;
	}
}